import com.mit.web.business.proxy.ManufactureProxy;
import com.mit.web.business.remote.IInvokeResponder;
import com.mit.web.config.Constants;
import com.mit.web.config.SizeGroupConfig;
import com.mit.web.event.PopWinCloseEvent;
import com.mit.web.util.DataFormatUtil;
import com.mit.web.util.FlexUtil;
import com.mit.web.view.component.grid.MOClipItemRenderer;
import com.mit.web.view.component.grid.MOItemRenderer;
import com.mit.web.view.component.monitor.IProgressMonitor;
import com.mit.web.vo.manufacture.MOItemVO;
import com.mit.web.vo.manufacture.MOVO;

import flash.events.MouseEvent;

import flexlib.scheduling.util.DateUtil;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.logging.ILogger;
import mx.resources.ResourceManager;
import mx.rpc.events.ResultEvent;

[Bindable] private var _order:MOVO
private var _proxy:ManufactureProxy = ManufactureProxy.getInstance();

private var _pm:IProgressMonitor;
private var _logger:ILogger;
private var _id:int;

public function set orderId(i:int):void{
	_id = i;
}

public function creationHandler(event:FlexEvent):void{
	//Load MO
	var resp:IInvokeResponder = _proxy.getMO(_id);
	resp.addResultListener(retrieveMOHandler);
	resp.addFaultListener(exceptionHandler);
}
private function retrieveMOHandler(event:ResultEvent):void{
	_order = event.result as MOVO;
	if(Constants.MO_STATE_NEW == _order.state){
		currentState = "newly";
		lbl_state.text = Constants.MO_STATES[0].label;
	}else if(Constants.MO_STATE_APPR == _order.state){
		currentState = "confirmed";
		lbl_state.text = Constants.MO_STATES[1].label;
	}else if(Constants.MO_STATE_CLIP == _order.state){
		currentState = "clipcomplete";
		lbl_state.text = Constants.MO_STATES[2].label;
	}else if(Constants.MO_STATE_COMPLETE == _order.state){
		currentState = "delivercomplete";
		lbl_state.text = Constants.MO_STATES[3].label;
	}
	//build item grid
	var sizeFields:ArrayCollection = _order.sizeFields;
	var sizeNames:ArrayCollection = SizeGroupConfig.getInstance().getSelectedSizes(_order.sizeGroup, sizeFields);
	for(var j:int = 0; j < sizeFields.length; j++){
		//下单数量
		var dgc:DataGridColumn = new DataGridColumn();		
		dgc.headerText = sizeNames[j] ;
		dgc.setStyle("headerStyleName","datagridHeader");
		dgc.setStyle("textAlign","right");
		dgc.sortable = false;
		dgc.width = 110;
		if(Constants.MO_STATE_CLIP == _order.state || Constants.MO_STATE_COMPLETE == _order.state)
			dgc.editable = false;
		if(Constants.MO_STATE_NEW == _order.state){
			//如果是未批准的，显示数量编辑
			
			dgc.dataField = sizeFields[j];
			dgc.itemEditor = new ClassFactory(com.mit.web.view.component.text.NumberTextInput);
		}else if(Constants.MO_STATE_APPR == _order.state){
			//已经批准的，可以修改裁床数量

			dgc.dataField = "p" +  sizeFields[j];
			dgc.editorDataField = "progress";
			dgc.itemEditor = new ClassFactory(com.mit.web.view.component.grid.MOClipNumberEditor);
			dgc.itemRenderer = new ClassFactory(com.mit.web.view.component.grid.MOClipItemRenderer);
		}else{

			dgc.dataField = "p" +  sizeFields[j];
			dgc.editable = false;
			dgc.itemRenderer = new ClassFactory(com.mit.web.view.component.grid.MOItemRenderer);
		}
		var cols:Array = dg.columns;
		cols.push(dgc);
		dg.columns = cols;

	}
	dg.validateNow();
}

private function doConfirm():void{
	//Validation
	if(validate() == false){

		return ;
	}
	
	//assemble vo
	assembleVO();
	var o:MOVO = FlexUtil.deepClone(_order) as MOVO;
	o.state = Constants.MO_STATE_APPR;

	var resp:IInvokeResponder = _proxy.saveMO(o);
	resp.addResultListener(updateMOHandler);
	resp.addFaultListener(exceptionHandler);
}

private function doSave(event:MouseEvent):void{
	//Validation
	if(validate() == false){
		event.preventDefault();
		return ;
	}
	
	//assemble vo
	assembleVO();
	
	var resp:IInvokeResponder = _proxy.saveMO(_order);
	resp.addResultListener(updateMOHandler);
	resp.addFaultListener(exceptionHandler);	
}

private function updateMOHandler(event:ResultEvent):void{
	var mo:MOVO = event.result as MOVO;
	var e:PopWinCloseEvent = new PopWinCloseEvent(PopWinCloseEvent.SAVED);
	e.vo = mo;
	e.msg = ResourceManager.getInstance()
		.getString(Constants.BUNDLE_COMMON,"info.common.saved",[mo.code]);
	this.dispatchEvent(e);
	closeWindow(this);
}

private function validate():Boolean{
	
	if(cmb_factory.selectedId < 1){
		showRequiredErrorTip(cmb_factory);
		return false;
	}
	if(txt_fee.number <= 0){
		showRequiredErrorTip(txt_fee);
		return false;
	}
	return true;
}

private function assembleVO():void{

	_order.creationDate = dat_creation.selectedDate;
	_order.deliverDate = DateUtil.addTime(DateUtil.copyDate(dat_creation.selectedDate), DateUtil.DAY_IN_MILLISECONDS * ns_deliver.value);
	_order.actualFee = txt_fee.number;
	_order.wholesalePrice = txt_wsPrice.number;
	_order.retailPrice = txt_retailPrice.number;
	_order.factoryId = cmb_factory.selectedId;
	_order.factoryName = cmb_factory.selectedItem.label;
	_order.remarks = txt_rmk.text;
	
	//sumup total qty in the item list;
	var totalQty:int = 0;
	var clipQty:int = 0;
	var sizeFields:ArrayCollection = _order.sizeFields;
	for each(var item:MOItemVO in _order.itemList){
		for each(var size:String in sizeFields){
			totalQty += item[size];
			clipQty += item["c" + size];
		}
	}
	_order.orderQty = totalQty;
	_order.clipQty = clipQty;
}

private function doDelete():void{
	var resp:IInvokeResponder = _proxy.deleteMO(_order.id);
	resp.addResultListener(deleteMOHandler);
	resp.addFaultListener(exceptionHandler);
}
private function deleteMOHandler(event:ResultEvent):void{
	var e:PopWinCloseEvent = new PopWinCloseEvent(PopWinCloseEvent.DELETED);	
	e.msg = ResourceManager.getInstance()
		.getString(Constants.BUNDLE_COMMON,"info.common.deleted",[_order.code]);
	this.dispatchEvent(e);
	closeWindow(this);	
}

private function doComp(event:MouseEvent):void{
	
	Alert.show("你确定已经交货完毕，可以结束该生产单吗？",
		ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"label.message.info"),
		Alert.YES|Alert.CANCEL, null	, completeConfirmHandler,null,Alert.CANCEL);
}

private function completeConfirmHandler(event:CloseEvent):void{
	if(event.detail == Alert.YES){
		//_order.state = Constants.MO_STATE_COMPLETE;
		//不能在这里设置_order的state，如果方法返回的是错误，则前台的数据的状态已经发生了变化，
		//应该在成功的handler中去设置_order的state
		var o:MOVO = FlexUtil.deepClone(_order) as MOVO;
		o.state = Constants.MO_STATE_COMPLETE;
		var resp:IInvokeResponder = _proxy.updateMOState(o);
		resp.addResultListener(completeMOHandler);
		resp.addFaultListener(exceptionHandler);
	}
}
private function completeMOHandler(event:ResultEvent):void{
	_order.state = Constants.MO_STATE_COMPLETE;
	var e:PopWinCloseEvent = new PopWinCloseEvent(PopWinCloseEvent.SAVED);	
	e.msg = ResourceManager.getInstance()
		.getString(Constants.BUNDLE_COMMON,"info.common.stateUpdate",[_order.code]);
	e.vo = _order;
	this.dispatchEvent(e);
	closeWindow(this);	
}

private function doCompClip(event:MouseEvent):void{
	//Validation
	if(validate() == false){
		event.preventDefault();
		return ;
	}
	
	//assemble vo
	assembleVO();
	
	Alert.show("确认后，系统将根据裁床数×工价自动添加应付款记录，你确定该生产单裁床工序已全部完成吗？",
		ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"label.message.info"),
		Alert.YES|Alert.CANCEL, null	, clipConfirmHandler,null,Alert.CANCEL);


}
private function clipConfirmHandler(event:CloseEvent):void{
	if(event.detail == Alert.YES){
		_order.state = Constants.MO_STATE_CLIP;
		var resp:IInvokeResponder = _proxy.saveMO(_order);
		resp.addResultListener(compClipMOHandler);
		resp.addFaultListener(exceptionHandler);
	}
}
private function compClipMOHandler(event:ResultEvent):void{
	var e:PopWinCloseEvent = new PopWinCloseEvent(PopWinCloseEvent.SAVED);	
	e.vo = _order;
	e.msg = ResourceManager.getInstance()
		.getString(Constants.BUNDLE_COMMON,"info.common.stateUpdate",[_order.code]);
	this.dispatchEvent(e);
	closeWindow(this);	
}

